package com.kwin;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * 完成一个手机验证码功能案例
 * 要求：
 *      1.输入手机号，点击发送后随机生成6位数字码，2分钟有效
 *      2.输入验证码，点击验证，返回成功或失败
 *      3.每个手机号每天只能输入3次
 */
public class PhoneCode {
    public static void main(String[] args) {
        verifyCode("13888888888");
        getRedisCode("13888888888","4444");
    }

    public static void getRedisCode(String phone, String code) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        String codeKey = "VerifyCode" + phone + ":code";
        String redisCode = jedis.get(codeKey);

        if (redisCode.equals(code)) {
            System.out.println("成功");
        } else {
            System.out.println("失败");
        }
        jedis.close();
    }

    public static void verifyCode(String phone) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        String countKey = "VerifyCode" + phone + ":count";
        String codeKey = "VerifyCode" + phone + ":code";

        String count = jedis.get(countKey);

        if (count == null) {
            jedis.setex(countKey,24*60*60,"1");
        } else if (Integer.parseInt(count) <= 2) {
            jedis.incr(codeKey);
        } else {
            System.out.println("今天发送次数已经超过了3次");
            jedis.close();
        }

        String vcode =getCode();
        jedis.setex(codeKey,300,vcode);
        jedis.close();
    }

    public static String getCode() {
        Random random = new Random();
        String code = "";
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            code += rand;
        }
        return code;
    }
}
